<?php

# http://projects:8081/cdapp-2kt-api/api/journal_position_record.php
include '_portal.php';

$method = $_GET['method'] ?? (MY_POST['method'] ?? '');

if ($method) {
  if ($method == 'SAVE') {
    save_position_record();
  } elseif ($method == 'GET_LAST_SUBMIT') {
    get_last_submit();
  }
}
die();

function save_position_record() {
  create_position_record_table();
  // create
  $case        = MY_POST['case'];
  $intensity   = MY_POST['intensity'];
  $levelBottom = MY_POST['levelBottom'];
  $levelTop    = MY_POST['levelTop'];
  $eventTime   = MY_POST['eventTime'];
  $x           = MY_POST['x'];
  $y           = MY_POST['y'];
  $seatIP      = MY_POST['seatIP'];
  $seatName    = MY_POST['seatName'];
  $seatUser    = MY_POST['seatUserName'];
  $sql         = "INSERT INTO `2kt_journal_position_record`(`case`, `intensity`, `levelBottom`, `levelTop`, `eventTime`, `x`, `y`, `seatIP`, `seatName`, `seatUser`) VALUES ('{$case}','{$intensity}','{$levelBottom}','{$levelTop}','{$eventTime}','{$x}','{$y}','{$seatIP}','{$seatName}','{$seatUser}')";
  $result      = exec_sql($sql);
  output(['success' => $result]);
  die();
}

function create_position_record_table() {
  $sql = "CREATE TABLE IF NOT EXISTS `2kt_journal_position_record` (
    `id` INT AUTO_INCREMENT PRIMARY KEY,
    `case` VARCHAR(255) NOT NULL,
    `intensity` INT NOT NULL,
    `levelBottom` INT NOT NULL,
    `levelTop` INT NOT NULL,
    `eventTime` DATETIME NOT NULL,
    `x` INT NOT NULL,
    `y` INT NOT NULL,
    `seatIP` VARCHAR(255) NOT NULL,
    `seatName` VARCHAR(255) NOT NULL,
    `seatUser` VARCHAR(255) NOT NULL,
    `updateTime` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
  )";
  $result = exec_sql($sql);
  return $result;
}

function get_last_submit() {
  $ip     = get_client_ip();
  $sql    = "SELECT * FROM `2kt_journal_position_record` WHERE `seatIP` = '{$ip}' ORDER BY `id` DESC LIMIT 1";
  $result = exec_sql($sql);
  if (! $result) {
    output(['result' => null, 'sql' => $sql]);
  } else {
    output(['result' => $result[0]]);
  }
  die();
}